// pages/goods_detail/index.js
import { request } from "../../request/index"
Page({

  data: {
    goodsDetail: {},
    urls: [],
    isCollect: false
  },
  goodinfo: {},


  onLoad: function (options) {

    this.getdetail(options)

  },

  async getdetail(goods_id) {
    const res = await request({ url: "https://api-hmugo-web.itheima.net/api/public/v1/goods/detail", data: goods_id })
    const urls = res.data.message.pics.map(e => e.pics_mid_url)
    this.goodinfo = res.data.message
    const collect = wx.getStorageSync("collect") || [];
    const index = collect.findIndex(e => e.goods_id === this.goodinfo.goods_id);
    this.setData({
      goodsDetail: {
        goods_price: res.data.message.goods_price,
        goods_name: res.data.message.goods_name,
        pics: res.data.message.pics,
        goods_introduce: res.data.message.goods_introduce

      },
      urls,

    })
    if (index !== -1) {
      this.setData({
        isCollect: true
      })
    } else {
      this.setData({
        isCollect: false
      })
    }


  },
  handlepreview(e) {
    const current = e.currentTarget.dataset.url
    wx.previewImage({
      current,
      urls: this.data.urls

    });


  },
  handleAddCart() {
    const cart = wx.getStorageSync("cart") || [];
    const index = cart.findIndex(e => e.goods_id === this.goodinfo.goods_id)
    if (index === -1) {
      this.goodinfo.num = 1
      this.goodinfo.checked = true
      cart.push(this.goodinfo)
    } else {
      cart[index].num++
    }
    wx.setStorageSync("cart", cart);
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      mask: true,

    });



  },
  handleCollect() {
    const isCollect = !this.data.isCollect;
    this.setData({
      isCollect
    })
    const collect = wx.getStorageSync("collect");

    if (this.data.isCollect) {

      wx.setStorageSync("collect", [...collect, this.goodinfo]);

    } else {
      const index = collect.findIndex(e => e.goods_id === this.goodinfo.goods_id);
      if (index !== -1) {
        collect.splice(index, 1)
        wx.setStorageSync("collect", collect)
      }
    }

  }

})